package com.atguigu.gmall.cart.listener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class CartMqListener {
    @Autowired
    StringRedisTemplate redisTemplate; //键和值必须是String类型
    Gson gson = new Gson();
    String cartPrefix = "cart:items:";

    @RabbitListener(bindings = @QueueBinding(
            value =  @Queue(value = "cart-checked-del-queue" , durable = "true" ,ignoreDeclarationExceptions = "true"),
            exchange = @Exchange(value = "order_exchange" , ignoreDeclarationExceptions = "true" ,type = ExchangeTypes.TOPIC),
            key = "cart.delete.checked"
    ))
    public void deleteCheckedCartItemsListener(Message message, Channel channel, Map<String,Object> map) throws IOException {
        try {
            //删除购物车中 订单中已选中的购物项
            String userId = map.get("userId").toString();
            String skuIdsJson = map.get("skuIds").toString();
            log.info("cart服务，删除选中的购物项列表监听器, userId: {} ， skuIdsJson: {}",
                   userId , skuIdsJson );
            List<String> skuIds = gson.fromJson(skuIdsJson , new TypeToken<List<String>>(){}.getType());
            //获取redis中userId的购物车
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartPrefix + userId);
            //如果skuIds中包含购物车的购物项  则删除购物项
            hashOps.delete(skuIds.toArray());//StringRedisTemplate 只能处理String类型的参数
            channel.basicAck(message.getMessageProperties().getDeliveryTag() , false);
        } catch (Exception e) {
            e.printStackTrace();
            if(message.getMessageProperties().isRedelivered()){
                channel.basicReject(message.getMessageProperties().getDeliveryTag() , false);
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag() , false , true);
            }
        }
    }
}
